package org.ms.mtx.example.controller;

import org.apache.commons.lang3.StringUtils;
import org.ms.mtx.core.annotation.Compensable;
import org.ms.mtx.example.service.PayService;
import org.ms.mtx.example.service.StockService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * The Example Controller
 *
 * @author lry
 */
@RestController
public class ExampleController {

    @Resource
    private StockService stockService;
    @Resource
    private PayService payService;

    /**
     * 模拟购买流程
     * <p>
     * 1 减库存
     * 2.1 支付
     * 2.2 增加积分
     *
     * @return Boolean
     */
    @Compensable
    @RequestMapping("buy")
    public Boolean buy(Integer number, Integer money, @RequestParam(required = false) String exceptionMock) {
        if (StringUtils.isNotBlank(exceptionMock) && exceptionMock.equals(Thread.currentThread().getStackTrace()[1].getMethodName())) {
            throw new RuntimeException("模拟异常:" + Thread.currentThread().getStackTrace()[1].getMethodName());
        }

        // 校验库存
        Boolean stockFlag = stockService.stock(number, exceptionMock);
        if (stockFlag) {
            // 校验余额
            return payService.pay(money, exceptionMock);
        }

        return false;
    }

}
